/**
 * 
 */
package jvs.peer.misc;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Duplicate the content from an input stream to an output stream. 
 * Mainly used for caching.
 * @author qiangli
 *
 */
public class CopyInputStream extends InputStream {
	private InputStream in;
	private OutputStream out;

	public CopyInputStream(InputStream in, OutputStream out) {
		this.in = in;
		this.out = out;
	}


	@Override
	public int read() throws IOException {
		int c = in.read();
		if (c != -1) {
			out.write(c);
		}
		return c;
	}

	@Override
	public int available() throws IOException {
		return in.available();
	}

	@Override
	public void close() throws IOException {
		in.close();
		out.close();
	}

	@Override
	public boolean markSupported() {
		return false;
	}

	@Override
	public void mark(int readlimit) {
		//
	}
	
	@Override
	public void reset() throws IOException {
		//
	}

	@Override
	public long skip(long n) throws IOException {
		return in.skip(n);
	}

	@Override
	public int read(byte[] b, int off, int len) throws IOException {
		if (len <= 0) {
			return -1;
		}
		int c = in.read(b, off, len);
		if (c != -1) {
			out.write(b, off, c);
		}
		return c;
	}

	@Override
	public int read(byte[] b) throws IOException {
		return read(b, 0, b.length);
	}
}
